package main;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.awt.Font;

import com.sun.xacml.Variables;
import com.sun.xacml.ctx.ResponseCtx;

import design.ViewPolicy;
import design.ViewRequest;
import design.ViewResponse;
import design.XMLViewer;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import javax.swing.SwingConstants;

public class DemoGeoPDP extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JTextField txtRequest;

	private File dir;
	private JLabel lblAttach;
	private int MAX = 100; 
	private JCheckBox[] chckbxTxtpolicy = new JCheckBox[MAX];
	private JLabel[] lblView = new JLabel[MAX];
	private JLabel lblRequest;
	private JButton btnRequest;
	private JLabel lblPolicy;

	private JFileChooser fc = new JFileChooser();

	private static int i = 0;
	private JButton btnExit;
	private JButton btnEvaluate;
	private MyFilter fJavaFilter = new MyFilter();

	public static void main(String[] args) {

		try {
			// set Look and Feel cho frame
			UIManager.setLookAndFeel(new MetalLookAndFeel());
			EventQueue.invokeLater(new Runnable() {

				public void run() {
					try {
						DemoGeoPDP frame = new DemoGeoPDP();
						frame.setVisible(true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		} catch (UnsupportedLookAndFeelException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/**
	 * Create the frame.
	 */
	public DemoGeoPDP() {
		
		// Choose only files, not directories
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fc.setFileFilter(fJavaFilter);
		
		setResizable(false);
		setTitle("Demo GeoPDP");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 494, 244);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		lblRequest = new JLabel("Request :");
		lblRequest.setFont(new Font("Times New Roman", Font.BOLD, 13));
		lblRequest.setToolTipText("");
		lblRequest.setBounds(12, 62, 59, 14);
		contentPane.add(lblRequest);

		txtRequest = new JTextField();
		txtRequest.setBounds(72, 56, 237, 20);
		contentPane.add(txtRequest);
		txtRequest.setColumns(10);

		lblPolicy = new JLabel("Policy :");
		lblPolicy.setFont(new Font("Times New Roman", Font.BOLD, 13));
		lblPolicy.setBounds(12, 117, 59, 14);
		contentPane.add(lblPolicy);

		btnRequest = new JButton("Browse");
		btnRequest.setToolTipText("Choose a request file");
		btnRequest.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dir = new File("C:/Documents and Settings/Admin/Desktop/sunxacml-1.2/sample/request");
				fc.setCurrentDirectory(dir);
				// Handle open button action.
				if (e.getSource() == btnRequest) {
					int returnVal = fc.showOpenDialog(DemoGeoPDP.this);

					if (returnVal == JFileChooser.APPROVE_OPTION) {
						File file = fc.getSelectedFile();
						// This is where a real application would open the file.
						txtRequest.setText(file.getPath());
					}
				}
			}
		});
		btnRequest.setFont(new Font("Times New Roman", Font.BOLD, 12));
		btnRequest.setBounds(321, 53, 82, 23);
		contentPane.add(btnRequest);

		ImageIcon icon = new ImageIcon("images/attach1.gif");
		lblAttach = new JLabel( icon, JLabel.LEFT);
		lblAttach.setVerticalAlignment(SwingConstants.BOTTOM);
		lblAttach.setToolTipText("add policies");
		lblAttach.setText("<html><u>Add files</u></html>");
		lblAttach.setFont(new Font("Times New Roman", Font.PLAIN, 12));
		lblAttach.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				fc.setMultiSelectionEnabled(true);
				dir = new File("C:/Documents and Settings/Admin/Desktop/sunxacml-1.2/sample/policy");
				fc.setCurrentDirectory(dir);
				if (e.getSource() == lblAttach) {
					int returnVal = fc.showOpenDialog(DemoGeoPDP.this);

					if (returnVal == JFileChooser.APPROVE_OPTION) {
						final File[] files = fc.getSelectedFiles();
						if(files.length == 0) ;
						if (files.length + i > MAX)
							JOptionPane.showMessageDialog(DemoGeoPDP.this,"Attach nhieu nhat " + MAX + " file ", "Error",JOptionPane.ERROR_MESSAGE);
						else {
							for (int j = 0; j < files.length; j++) {
								chckbxTxtpolicy[i] = new JCheckBox("CheckBox",true);
								chckbxTxtpolicy[i].setBounds(52, 141 + 25 * i,150, 24);
								chckbxTxtpolicy[i].setText(files[j].getName());
								chckbxTxtpolicy[i].setName(files[j].getPath());
								contentPane.add(chckbxTxtpolicy[i]);
								ImageIcon icon = new ImageIcon("images/view1.gif");
								lblView[i] = new JLabel(icon, JLabel.CENTER);
								lblView[i].setToolTipText("View this file");
								lblView[i].setBounds(203, 141 + 25 * i, 25, 25);
								lblView[i].addMouseListener(new MouseAdapter() {
									@SuppressWarnings("deprecation")
									public void mouseClicked(MouseEvent e) {
										int no = 0;
										for (int k = 0; k < i; k++) {
											if (e.getSource() == lblView[k]) {
												no = k;
												break;
											}
										}
										try {
											String fileName = chckbxTxtpolicy[no].getName();
											DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
											DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
											Document doc = docBuilder.parse(new File(fileName));
											if (doc.getElementsByTagName("PolicySet").getLength() == 0
													&& doc.getElementsByTagName("Policy").getLength() == 0) {
												JOptionPane.showMessageDialog(DemoGeoPDP.this,"This file is not a valid policy file.Please choose again!","Warning",JOptionPane.WARNING_MESSAGE);
												chckbxTxtpolicy[no].setSelected(false);
											} else {
												XMLViewer view = new XMLViewer(chckbxTxtpolicy[no].getName(),"View Policy");
												view.show();
												//ViewPolicy view = new ViewPolicy(chckbxTxtpolicy[no].getName());
												//view.show();
											}
										} catch (Exception e1) {
											// TODO Auto-generated catch block
											e1.printStackTrace();
										}
									}
								});
								contentPane.add(lblView[i]);
								i = i + 1;
								setBounds(100, 100, 490, 244 + 25 * i);
								btnEvaluate.setBounds(128, 165 + 25 * i, 89, 23);
								btnExit.setBounds(248, 165 + 25 * i, 89, 23);
							}
						}
					}
				}
			}
		});
		lblAttach.setBounds(82, 98, 100, 33);
		contentPane.add(lblAttach);
		JButton btnViewRequest = new JButton("View");
		btnViewRequest.setToolTipText("View selected request file");
		btnViewRequest.addActionListener(new ActionListener() {
			@SuppressWarnings("deprecation")
			public void actionPerformed(ActionEvent e) {
				if (txtRequest.getText().equals("")) {
					JOptionPane.showMessageDialog(DemoGeoPDP.this,
							"Please choose a request file to view", "Error",
							JOptionPane.ERROR_MESSAGE);
				} else {
					XMLViewer view = new XMLViewer(txtRequest.getText(),"View Request");
					view.show();
				//	ViewRequest viewRequest = new ViewRequest(txtRequest.getText());
					//viewRequest.show();						
				}
			}
		});
		btnViewRequest.setFont(new Font("Times New Roman", Font.BOLD, 12));
		btnViewRequest.setBounds(406, 53, 68, 23);
		contentPane.add(btnViewRequest);

		btnEvaluate = new JButton("Evaluate");
		btnEvaluate.addActionListener(new ActionListener() {
			@SuppressWarnings("deprecation")
			public void actionPerformed(ActionEvent e) {
				SpatialPDP simplePDP = null;

				Variables.requestFileName = txtRequest.getText();
				if (Variables.requestFileName.equals("")) {
					JOptionPane.showMessageDialog(DemoGeoPDP.this,
							"Choose a request file to evaluate", "Error",
							JOptionPane.ERROR_MESSAGE);
				} else {
					int length = 0;
					for (int k = 0; k < i; k++) {
						if (chckbxTxtpolicy[k].isSelected())
							length += 1;						
					}
					for( int b = i - 1 ; b >= length ; b--)
					{
						contentPane.remove(chckbxTxtpolicy[b]);
						contentPane.remove(lblView[b]);
						btnEvaluate.setBounds(128, 155 + 25 * length,89, 23);				
						btnExit.setBounds(248, 155 + 25 * length, 89, 23);						
						setBounds(100, 100, 490, 244 + 25 * length);
					}
					for (int a = 0; a < length; a++) {
						if (!chckbxTxtpolicy[a].isSelected()) {
							for (int c = a; c < i; c++) {
								if (chckbxTxtpolicy[c].isSelected()) {
									chckbxTxtpolicy[a].setName(chckbxTxtpolicy[c].getName());
									chckbxTxtpolicy[a].setText(chckbxTxtpolicy[c].getText());
									chckbxTxtpolicy[a].setSelected(true);
									chckbxTxtpolicy[c].setSelected(false);
									break;
								}
							}
						}						
					}
					ResponseCtx response;
					if (length == 0) {
						try {							
							simplePDP = new SpatialPDP();
							// evaluate the request
							response = simplePDP
									.evaluate(Variables.requestFileName);
							ViewResponse viewResponse = new ViewResponse(response);
							viewResponse.show();
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					} else {
						Variables.policiesFileName = new String[length];
						int j = 0;
						for (int k = 0; k < i; k++) {
							if (chckbxTxtpolicy[k].isSelected()) {
								Variables.policiesFileName[j] = chckbxTxtpolicy[k].getName();
								//System.out.println( Variables.policiesFileName[j] + " ***************************************");
								j = j + 1;
							}
						}					
						try {
							simplePDP = new SpatialPDP(Variables.policiesFileName);
							// evaluate the request
							response = simplePDP
									.evaluate(Variables.requestFileName);
						
							ViewResponse viewResponse = new ViewResponse(response);
							viewResponse.show();
						} catch (Exception e2) {
							// TODO Auto-generated catch block
							e2.printStackTrace();
						}				
					}					
					i = length ;
				}
			}
		});
		btnEvaluate.setFont(new Font("Times New Roman", Font.BOLD, 12));
		btnEvaluate.setBounds(128, 155, 89, 23);
		contentPane.add(btnEvaluate);

		btnExit = new JButton("Exit");
		btnExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		btnExit.setFont(new Font("Times New Roman", Font.BOLD, 12));
		btnExit.setBounds(248, 155, 89, 23);
		contentPane.add(btnExit);
	}

	class MyFilter extends javax.swing.filechooser.FileFilter {
		public boolean accept(File file) {
			String filename = file.getName();
			return filename.toLowerCase().endsWith(".xml");
		}

		public String getDescription() {
			return "Xml files (*.xml)";
		}
	}
}
